package mi.payment.utils.iso8583;

import java.text.SimpleDateFormat;

import mi.payment.MyApplication;
import mi.payment.constants.Configs;
import mi.payment.utils.SNUtils;
import sunmi.sunmiui.utils.LogUtil;

/**
 * 组59域，21号文
 *
 * @author Lee64 on 2017/6/27.
 */

public class Composition59Util {

    /**
     * 银行卡21号文
     */
    public static String get59Data(String cardNo) {
        String valueA2 = getA2TagData(cardNo);
        StringBuilder sb = new StringBuilder();
        sb.append("A2");
        String len = getLen(valueA2);
        sb.append(len);
        sb.append(valueA2);
        return sb.toString();
    }

    /**
     * 扫码付21号文
     */
    public static String getQRCode59Data(String C2B) {
        String valueA2 = getA2TagData(C2B);
        StringBuilder sb = new StringBuilder();
        sb.append("A2");
        String len = getLen(valueA2);
        sb.append(len);
        sb.append(valueA2);
        return sb.toString();
    }

    private static String getA2TagData(String cardNo) {
        StringBuilder sb = new StringBuilder();

        // 设备类型 TAG 01
        sb.append("0100204");

        // 终端硬件序列号 TAG 02
        // 6位厂商编号000043 + 2位终端类型04
        String sn = SNUtils.getTUSN();
        sb.append("02");
        sb.append(getLen(sn));
        sb.append(sn);

        // 加密随机因子 TAG 02
        int length = cardNo.length();
        String encryptionRandomFactor = cardNo.substring(length - 6, length);
        sb.append("03");
        sb.append("006");
        sb.append(encryptionRandomFactor);

        // 硬件序列号密文数据 TAG 04
        String encryptionData = "00000000";
        byte[] dataOut = new byte[4];
        try {
            int result = MyApplication.app.securityOpt.getEncryptTUSN(encryptionRandomFactor, dataOut);
            LogUtil.e(Configs.TAG, "21号文加密结果：" + result);
            if (result == 0) {
                encryptionData = Utils.byte2HexStr(dataOut);
                LogUtil.e(Configs.TAG, "21号文加密字符串：" + encryptionData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        sb.append("04");
        sb.append("008");
        sb.append(encryptionData);

        // 应用程序版本号 TAG 05
        sb.append("05");
        sb.append("008");
        String versionCode = get21VersionCode();
        sb.append(versionCode);
        return sb.toString();
    }

    private static String getLen(String str) {
        String len;
        int length = str.length();
        if (length < 10) {
            len = "00" + length;
        } else if (length < 100) {
            len = "0" + length;
        } else {
            len = String.valueOf(length);
        }
        return len;
    }

    private static String get21VersionCode() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        return "20180912";
    }


}
